﻿#ifndef SSQLCONNECTIONPOOL_H
#define SSQLCONNECTIONPOOL_H

#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlRecord>


#include <QMutex>
#include <QMutexLocker>
#include <Qqueue>
#include <QWaitCondition>
#include <QDateTime>
#include <QWidget>


class SSqlconnectionPool:public QWidget
{
	Q_OBJECT

	SSqlconnectionPool(QWidget* parent = nullptr);

public:
	void layoutinit();

private:
	quint16 m_port;
	QString m_hostname;
	QString m_databasename;
	QString m_username;
	QString m_password;
	QString m_databseType;


	QMutex m_openMutex;							//互斥量
	QWaitCondition m_waitCond;					//条件
	quint32 m_waitInterval;							//等待间隔 毫秒
	quint32 m_waitTime;								//等待次数
	quint32 m_maxconnectioncount;				//最大连接数
	QQueue<QString> m_useConnections;			//已经被使用的连接量
	QQueue<QString> m_unuseConnections;			//还没有被使用的连接量

public:
	size_t useConnections() const
	{
		return m_useConnections.count();
	}
	size_t unuseConnections() const
	{
		return m_unuseConnections.count();
	}
signals:
	void SqlData(QString);

public:
	static SSqlconnectionPool* instance();
	~SSqlconnectionPool();

	QSqlDatabase openConnection();
	void closeConnection(QSqlDatabase db);

	void setPort(const quint16& port)
	{
		m_port = port;
	}
	void setHostname(const QString& hostname)
	{
		m_hostname = hostname;
	}
	void setDatabasename(const QString& databasename)
	{
		m_databasename = databasename;
	}
	void setUsername(const QString& username)
	{
		m_username = username;
	}
	void setPassword(const QString& password)
	{
		m_password = password;
	}



private:
	QSqlDatabase createConnection(const QString& con_name);
	void releaseConnection(QSqlDatabase db);

	friend class SConnectionWarp;

};

//辅助类；用于帮助	SSqlconnectionPool 类	进行	连接的打开和关闭
class SConnectionWarp
{
private:
	QSqlDatabase m_db;
public:
	SConnectionWarp();
	~SConnectionWarp();

	QSqlDatabase openConnection();
};



#endif // !SSQLCONNECTIONPOOL_H
